<template>
  <div class="login-wrapper">
    <div class="login-wrapper-title">
      <div class="login-wrapper-icon">
        <van-image width="120" height="120" :src="hmIcon" />
      </div>
      <div class="login-wrapper-titles">惠麦电商供应链平台{{ getEnvValue("VITE_APP_NEED_HEAD") ? '(' +
        getEnvValue("VITE_APP_NEED_HEAD") + ')' : '' }}</div>
      <div class="register_button" @click="registerClick" v-if="isVersions === '1'">注册</div>
    </div>
    <van-cell-group inset>
      <div class="login-wrapper-label">登录账号</div>
      <van-field v-model="username" placeholder="请输入账号">
        <template #left-icon>
          <svg-icon icon="loginUser" />
        </template>
      </van-field>
      <div class="login-wrapper-label login-wrapper-pwd">登录密码</div>
      <van-field v-model="password" type="password" placeholder="请输入密码">
        <template #left-icon>
          <svg-icon icon="password" />
        </template>
      </van-field>
    </van-cell-group>
    <div class="forgetPassword">
      <div @click="handleForget">忘记密码</div>
    </div>
    <div class="login-wrapper-btn" @click="handleLogin" v-throttle:click>
      登 录
    </div>

    <div class="login-index-policy">
      <div class="checkbox-container" @click="checked = !checked">
        <van-checkbox icon-size="16px" v-model="checked">同意条款</van-checkbox>
      </div>
      <!-- <van-checkbox icon-size="16px" v-model="checked"></van-checkbox> -->
      <div class="login-index-policy-text">
        <div>
          我已阅读并同意
          <span class="login-index-policy-text-rules" @click="goPrivacyAgreement">《隐私政策》</span>
          和
          <span class="login-index-policy-text-rules" @click="goPrivacyAgreements">《用户协议》</span>
        </div>

      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { showSuccessToast, showFailToast } from "vant";
import { useRoute, useRouter } from "vue-router";
import { computed, reactive, ref, toRefs, watch, onMounted } from "vue";
import { apiLogin } from "@/api/loginApi";
import { getInfo } from "@/api/supplierList/index";
import { getVersion } from '@/api/productHome/index'
import { loginStore } from "@/store/login";
import { userStore } from "@/store/user";
import { getEnvValue } from "@/utils/index";
import { storeToRefs } from "pinia";
const store = loginStore();
const { token } = storeToRefs(store);
const hmIcon = new URL("@/assets/login/icon_logo.png", import.meta.url).href;
const checked = ref(false)
const isVersions = ref('')
const route = useRoute();

// 隐私协议是否勾选
const checkedFlag = computed(() => {
  return route.query.checked;
});
onMounted(() => {
  getVersions()
})

const register = async () => {
  (window as any).uni.webView.postMessage({
    data: {
      type: "register",
      name: "register",
      Authorization: `Bearer ${token.value}`,
    },
  });
}
const getVersions = async () => {
  const { rows = [] } = await getVersion()
  isVersions.value = rows[0].allowRegister
}
watch(
  () => checkedFlag.value,
  (v: any) => {
    checked.value = v == '1' ? true : false
  },
  { immediate: true }
)

const loginEffect = () => {
  const user = userStore();
  const login = loginStore();
  const router = useRouter();
  const loginForm = reactive({ username: "", password: "" });
  const { username, password } = toRefs(loginForm);
  const loginValidate = () => {
    if (!username.value || !password.value) {
      showFailToast("账号或密码不能为空！");
      return false;
    }
    return true;
  };
  const handleLogin = async () => {
    if (checked.value) {
      if (loginValidate()) {
        const result = await apiLogin({
          username: username.value,
          password: password.value,
          tenantId: "000000",
          clientId: "e5cd7e4891bf95d1d19206ce24a7b32e",
          grantType: "password",
          rememberMe: false,
        });
        const { access_token } = result.data;
        login.setToken(access_token);
        // await user.getProfile(token)
        const res = await getInfo()
        user.setuser(res.data.roles)
        register()
        if (res.data.roles.indexOf('app') !== -1) {
          user.setuser(['app'])
          showSuccessToast("登录成功！");
          router.push("/forge");
        } else if (res.data.user.roles[0].roleKey.indexOf('recruit') != -1) { // 招商部
          showSuccessToast("登录成功！");
          router.push("/home");
        } else if (res.data.user.roles[0].roleKey.indexOf('superadmin') != -1) { // 超级管理员
          showSuccessToast("登录成功！");
          router.push("/home");
        } else if (res.data.user.roles[0].roleKey.indexOf('stock') != -1) { //产品
          showSuccessToast("登录成功！");
          router.push("/productHome");
        } else if (res.data.user.roles[0].roleKey.indexOf('core') != -1) { // 主播运营
          showSuccessToast("登录成功！");
          router.push("/operation");
        } else if (res.data.user.roles[0].roleKey.indexOf('selectionOfficer') != -1) { // 选品官
          showSuccessToast("登录成功！");
          router.push("/selection");
        } else if (res.data.user.roles[0].roleKey.indexOf('invent') != -1) { // 研发
          showSuccessToast("登录成功！");
          router.push("/research");
        }
        else {
          showFailToast('对不起, 您的账号不存在！')
          login.resetToken()
        }
      }
    } else {
      showFailToast("请阅读并勾选惠麦供应链管理系统隐私政策");
    }
  };
  /** 用户隐私协议 */
  const goPrivacyAgreement = () => {
    router.push({
      path: '/policy',
      query: {
        checked: checked.value ? '1' : '0'
      }
    });
  }
  /** 用户用户协议 */
  const goPrivacyAgreements = () => {
    router.push({
      path: '/userAgreement'
    });
  }
  /** 忘记密码 */
  const handleForget = () => {
    router.push({
      path: '/forgetPassword'
    });
  }
  const registerClick = () => {
    router.push({
      path: '/register'
    });
  }
  return { username, password, handleLogin, goPrivacyAgreement, goPrivacyAgreements, handleForget, registerClick };
};






const { username, password, handleLogin, goPrivacyAgreement, goPrivacyAgreements, handleForget, registerClick } = loginEffect();
</script>

<style lang="less" scoped>
@import "@/styles/views/login.less";
.checkbox-container {
  height: 30px;
  width: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.checkbox-container .van-checkbox {
  pointer-events: none; /* 禁止内部元素的点击事件 */
}
.forgetPassword {
  font-weight: 500;
  font-size: 14px;
  color: #AFB6C3;
  box-sizing: border-box;
  padding: 10px 16px;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: flex-end;

  div {
    width: 60px;
  }
}
</style>
